package com.junson.Interceptor;

import java.util.Locale;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerMapping;
import org.springframework.web.servlet.i18n.LocaleChangeInterceptor;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

@Component
public class LanguageInterceptor extends LocaleChangeInterceptor{
	
	private Logger logger = LoggerFactory.getLogger(getClass());
	private SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
	
	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws ServletException {
		Object object = request.getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
		Locale locale = new Locale("zh", "CN");
		sessionLocaleResolver.setDefaultLocale(locale);
		if(!StringUtils.isEmpty(object) ) {
			@SuppressWarnings("unchecked")
			Map<String, String> map =  (Map<String, String>)object;  
			if ("en".equalsIgnoreCase(map.get("lang"))) {
				locale = new Locale(map.get("lang").toLowerCase(), "US");
			}
		}
		logger.info("local language[{}] country[{}]", locale.getLanguage(), locale.getCountry());
		sessionLocaleResolver.setLocale(request, response, locale);
		
		return super.preHandle(request, response, handler);
	}
	
	public SessionLocaleResolver sessionLocaleResolver() {
		return sessionLocaleResolver;
	}

}
